package com.fumin.controller;

import com.fumin.model.SysUser;
import com.fumin.service.SysUserService;
import com.fumin.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author xiayuxuanmin
 * @Date 2019/10/25
 * @Description
 */
@Controller
//@RequestMapping("/user")
public class UserController {

    @Resource
    private SysUserService sysUserService;

    @RequestMapping("/logout.page")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        String path = "signin.jsp";
        response.sendRedirect(path);
    }

    /**
     * 登录验证
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/login.page")
    public void login(HttpServletResponse response,HttpServletRequest request) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        SysUser sysUser = sysUserService.findByKeyword(username);
        String ret = request.getParameter("ret");//请求想跳转的链接
        String errorMsg = "";
        if (StringUtils.isBlank(username)) {
            errorMsg = "用户名不可以为空！";
        }else if(StringUtils.isBlank(password)){
            errorMsg = "密码不可以为空！";
        }else if(sysUser == null){
            errorMsg = "查询不到指定的用户！";
        }else if (!sysUser.getPassword().equals(MD5Util.encrypt(password))){
            errorMsg = "用户名或密码错误！";
        }else if(!sysUser.getStatus().equals(1)){
            errorMsg = "用户已被冻结，请联系管理员！";
        }else{
            //登录成功
            request.getSession().setAttribute("user",sysUser);
            if (StringUtils.isNotBlank(ret)) {
                //跳转到请求中的ret地址
                response.sendRedirect(ret);
            }else{
                //跳转到默认地址
                response.sendRedirect("/admin/index.page");
            }
        }
        //登录失败，跳转到登录界面
        request.setAttribute("error",errorMsg);
        request.setAttribute("username",username);
        if (StringUtils.isNotBlank(ret)) {
            request.setAttribute("ret",ret);
        }
        String path = "signin.jsp";//这个会带上类上的@RequestMapping("/user")的路径，而实际上是不需要的，所以移除@RequestMapping("/user")
        request.getRequestDispatcher(path).forward(request,response);
    }
}
